﻿using System;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Text;
using Texfina.Core.Common;
using Texfina.Common.Mg;
using Texfina.Core.Web;
using Texfina.Core.Data;
using Texfina.Entity.Rh;
using Texfina.Entity.Mg;
using Texfina.Entity.Sy;
using RHBOQry = Texfina.BOQry.Rh;
using MGBOQry = Texfina.BOQry.Mg;
using RHBOMnt = Texfina.BOMnt.Rh;
using SYBOQry = Texfina.BOQry.Sy;

namespace RH
{
    public partial class wfAFPMnt : EditPage
    {

        public const int _GRDLIST_IDMES = 1;
        public const int _GRDLIST_STANULADO = 9;


        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (this.IsPostBack)
                {
                    this.LoadInPostBack();
                    return;
                }
                this.LoadData();
            }
            catch (Exception ex)
            {
                this.hdnMsgOPB.Value = this.CreatePostbackMessage("ERROR", ex.Message, TypeMessageAlert.error, false, "");
            }
        }

        public override void LoadInPostBack()
        {
            this.RegisterGeneralScripts();
        }

        public override void LoadInitialSettings()
        {
            Label lbl = (Label)this.Master.FindControl("lblTitle");
            lbl.Text = "Conceptos Remunerativos";
            this.FormEditAction = (FormEditAction)Enum.Parse(typeof(FormEditAction), Request.QueryString["formEA"]);
            this.SetInitialTitle("AFP");
        }

        public override void LoadListControls()
        {
            try
            {
                ETablaGenDet objEDet = new ETablaGenDet();
                MGBOQry.ITablaGen objBOI = (MGBOQry.ITablaGen)WCFHelper.GetObject<MGBOQry.ITablaGen>(typeof(MGBOQry.TablaGen));

                objEDet.IdTabla = ConstMultitabla.MES;
                DataTable dt = objBOI.GetDetailByList(objEDet);
                WebHelper.LoadListControl(ddlidMes, dt, "dsDescrip", "idCodigo", true, true);

                objEDet.IdTabla = ConstMultitabla.TIPO_COMISION_AFP;
                dt = objBOI.GetDetailByList(objEDet);
                WebHelper.LoadListControl(ddlidTipComision, dt, "dsDescrip", "idCodigo", true, true);

                objEDet.IdTabla = ConstMultitabla.FACTOR_CALCULO_PLANILLA;
                dt = objBOI.GetDetailByList(objEDet);
                WebHelper.LoadListControl(ddlidTipValor, dt, "dsDescrip", "idCodigo", true, true);
            }
            catch (Exception ex)
            {
                this.hdnMsgOPB.Value = this.CreatePostbackMessage("ERROR", ex.Message, TypeMessageAlert.error, false, "");
            }
        }

        public override void DataToControls()
        {
            try
            {
                EAfp objE = new EAfp();
                IBOQuery objBO = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(RHBOQry.Afp));
                objE.IdAfp = Request.QueryString["IdAfp"];
                objE = (EAfp)objBO.GetByKey(objE);

                if (objE != null)
                {
                    WebHelper.EntityToControl(objE, "IdAfp", txtidAfp);
                    WebHelper.EntityToControl(objE, "DsAfp", txtdsAfp);
                    WebHelper.EntityToControl(objE, "DsAbrev", txtdsAbrev);
                }

                EAfpComi objEDet = new EAfpComi();
                RHBOQry.IAfp objBODet = (RHBOQry.IAfp)WCFHelper.GetObject<RHBOQry.IAfp>(typeof(RHBOQry.Afp));
                objEDet.IdAfp = Request.QueryString["IdAfp"];
                objEDet.IdPeriodo = Session[ConstSessionVar.PERIODO].ToString();
                DataTable dt = objBODet.GetByParentKeyAfpComi(objEDet);
                this.GridSetDataBinding(grdList, dt);
            }
            catch (Exception ex)
            {
                this.hdnMsgOPB.Value = this.CreatePostbackMessage("ERROR", ex.Message, TypeMessageAlert.error, false, "");
            }
        }

        public override void RegisterGeneralScripts()
        {
            txtidAfp.Attributes.Add("readonly", "true");
            ddlidMes.Attributes.Add("disabled", "true");
            ddlidTipComision.Attributes.Add("disabled", "true");

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("function validateEditForm(key){");
            sb.AppendLine("var varRpta = isEmptyControl('" + txtdsAfp.ClientID + "','Ingrese La Razon social de la AFP');");
            sb.AppendLine("if(varRpta==true){");
            sb.AppendLine("document.getElementById('" + txtdsAfp.ClientID + "').focus();return !varRpta;}");

            //sb.AppendLine("var varRpta = isEmptyControl('" + txtdsAbrev.ClientID + "','Ingrese la Abreviatura del AFP');");
            //sb.AppendLine("if(varRpta==true){");
            //sb.AppendLine("document.getElementById('" + txtdsAbrev.ClientID + "').focus();return !varRpta;}");

            //sb.AppendLine("function validateEditFormGrid(key){");
            //sb.AppendLine("varRpta = gridFindCellValueInRow('" + grdList.ClientID + "',new Array(" + _GRDLIST_IDMES + "," + _GRDLIST_STANULADO + "), new Array(" + ddlidMes.SelectedItem.Value + "," + ConstFlagEstado.DESACTIVADO + "),'Solo registrar un tipo de comisión por mes , Verifiquelo.');");
            //sb.AppendLine("if(varRpta==true)");
            //sb.AppendLine("return !varRpta;");

            sb.AppendLine("menu_doPostBack('" + mnuToolbar.ClientID + "','" + mnuToolbar.UniqueID + "',key);");
            sb.AppendLine("}");

            ScriptManager.RegisterStartupScript(this, this.GetType(), "ScriptRegister", sb.ToString(), true);
        }

        public void RegisterEditPopupScripts()
        {
        }

        protected void mnuToolbar_MenuItemClick(Object sender, MenuEventArgs e)
        {
            try
            {
                if (e.Item == null)
                    return;

                switch (e.Item.Value)
                {
                    case ConstMenuToolbarValue.BUTTON_SAVE:
                    case ConstMenuToolbarValue.BUTTON_SAVENEW:
                        if (this.FormEditAction != FormEditAction.Delete)
                            this.SaveData(e.Item.Value);
                        else
                            this.DeleteData();
                        break;

                    case ConstMenuToolbarValue.BUTTON_EXIT:
                        this.Response.Redirect("wfAFPBnd.aspx?Filter=1");
                        break;
                }
            }
            catch (Exception ex)
            {
                this.hdnMsgOPB.Value = this.CreatePostbackMessage("ERROR", ex.Message, TypeMessageAlert.error, false, "");
            }
        }

        protected void mnuGrid_MenuItemClick(Object sender, MenuEventArgs e)
        {
            try
            {
                if (e.Item == null)
                    return;

                switch (e.Item.Value)
                {
                    case ConstMenuToolbarValue.BUTTON_NEW:
                        this.GridEditAction = GridEditAction.AddNew;
                        this.lblTitlePopup.Text = "Comisión AFP (Nuevo)";
                        this.mdlPopup.Show();
                        this.LoadDataEditPopup(grdList, -1);
                        this.RegisterEditPopupScripts();
                        break;
                }
            }
            catch (Exception ex)
            {
                this.hdnMsgOPB.Value = this.CreatePostbackMessage("ERROR", ex.Message, TypeMessageAlert.error, false, "");
            }
        }

        protected void grdList_RowCommand(Object sender, GridViewCommandEventArgs e)
        {
            this.EditRowIndex = Convert.ToInt32(e.CommandArgument);

            switch (e.CommandName)
            {
                case ConstGridRowCommand.GRIDEDIT:
                    this.lblTitlePopup.Text = "Comisión AFP (Editar)";
                    this.GridEditAction = GridEditAction.Edit;
                    this.mdlPopup.Show();
                    this.LoadDataEditPopup(grdList, this.EditRowIndex);
                    this.RegisterEditPopupScripts();
                    break;

                case ConstGridRowCommand.GRIDDELETE:
                    this.lblTitlePopup.Text = "Comisión AFP (Eliminar)";
                    this.GridEditAction = GridEditAction.Delete;
                    this.mdlPopup.Show();
                    this.LoadDataEditPopup(grdList, this.EditRowIndex);
                    this.RegisterEditPopupScripts();
                    break;
            }
        }

        protected void grdList_RowDataBound(Object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                String strRI = e.Row.RowIndex.ToString();

                ImageButton bttedit = (ImageButton)e.Row.FindControl("grdBtt" + ConstGridRowCommand.GRIDEDIT);
                ImageButton bttdelete = (ImageButton)e.Row.FindControl("grdBtt" + ConstGridRowCommand.GRIDDELETE);

                bttedit.OnClientClick = "javascript:return validateGridCommands('" + ConstGridRowCommand.GRIDEDIT + "','" + strRI + "');";
                bttdelete.OnClientClick = "javascript:return validateGridCommands('" + ConstGridRowCommand.GRIDDELETE + "','" + strRI + "');";

                if (e.Row.Cells[_GRDLIST_STANULADO].Text == ConstFlagEstado.ACTIVADO)
                {
                    e.Row.ForeColor = System.Drawing.Color.Red;
                    bttedit.ImageUrl = "../Images/Icons/Disabled/Edit.png";
                    bttdelete.ImageUrl = "../Images/Icons/Disabled/Delete.png";
                }
            }

        }

        protected void bttOkPopup_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable dt = (DataTable)this.DataSource;
                DataRow dr = null;

                if (this.GridEditAction == GridEditAction.AddNew || this.GridEditAction == GridEditAction.Copy)
                {
                    dr = dt.NewRow();
                }
                else
                {
                    dr = this.GridGetRowFromDataKey(grdList, this.EditRowIndex);
                }

                if (this.GridEditAction != GridEditAction.Delete)
                {
                    dr["idAfp"] = Request.QueryString["IdAfp"];
                    dr["idPeriodo"] = Session[ConstSessionVar.PERIODO].ToString();
                    dr["idTipoValor"] = this.ddlidTipValor.SelectedItem.Value;
                    dr["dsTipoValor"] = this.ddlidTipValor.SelectedItem.Text;
                    dr["nuValor"] = this.txtmtValor.Value;
                    dr["stAnulado"] = ConstFlagEstado.DESACTIVADO;
                }
                else
                {
                    dr["stAnulado"] = ConstFlagEstado.ACTIVADO;
                }

                if (this.GridEditAction == GridEditAction.AddNew || this.GridEditAction == GridEditAction.Copy)
                {
                    dt.Rows.Add(dr);
                }


                this.GridSetDataBinding(grdList, dt);
            }
            catch (Exception ex)
            {
                this.hdnMsgOPB.Value = this.CreatePostbackMessage("ERROR", ex.Message, TypeMessageAlert.error, false, "");
            }
        }

        public override void LoadDataEditPopup(GridView grid, int rowIndex)
        {
            this.ClearEditPopup();
            this.LockControlsPopup();

            DataRow dr = this.GridGetRowFromDataKey(this.DataSource, grdList, rowIndex);

            if (dr == null)
                return;

            WebHelper.RowToControl(dr, "idMes", ddlidMes);
            WebHelper.RowToControl(dr, "idTipoComi", ddlidTipComision);
            WebHelper.RowToControl(dr, "idTipoValor", ddlidTipValor);
            WebHelper.RowToControl(dr, "nuValor", txtmtValor);

        }

        public new void ClearEditPopup()
        {
            this.txtmtValor.Text = "";
            this.ddlidMes.SelectedIndex = 0;
            this.ddlidTipComision.SelectedIndex = 0;
            this.ddlidTipValor.SelectedIndex = 0;
        }

        public void LockControlsPopup()
        {
            if (this.GridEditAction == GridEditAction.Delete)
            {
                this.ddlidMes.Enabled = false;
                this.ddlidTipComision.Enabled = false;
                this.ddlidTipValor.Enabled = false;
                this.txtmtValor.Enabled = false;
            }
        }

        public override void SaveData(String key)
        {
            if (this.ValidateData() == false)
                return;

            IEntityBase objE = (IEntityBase)this.CreateEntitySet();
            IBOUpdate objPro = (IBOUpdate)WCFHelper.GetObject<IBOUpdate>(typeof(RHBOMnt.Afp));

            String[] strRet = objPro.UpdateData(objE);
            String strMsg = "";

            switch (this.FormEditAction)
            {

                case FormEditAction.AddNew:
                case FormEditAction.Copy:
                    strMsg = "Se ha registrado la AFP : " + strRet[0].ToString() + " - " + strRet[1].ToString();
                    break;
                default:
                    strMsg = "Se ha modificado la Afp : " + txtidAfp.Text + "-" + txtdsAfp.Text;
                    break;
            }
            this.hdnMsgOPB.Value = this.CreatePostbackMessage("CORRECTO", strMsg, TypeMessageAlert.correct, false, "wfAFPBnd.aspx?Filter=1");
        }

        public override void DeleteData()
        {
            IEntityBase objE = (IEntityBase)this.CreateEntitySet();
            IBOUpdate objPro = (IBOUpdate)WCFHelper.GetObject<IBOUpdate>(typeof(RHBOMnt.Afp));
            objPro.DeleteData(objE);

            this.hdnMsgOPB.Value = this.CreatePostbackMessage("CORRECTO", "Se anulo la AFP : " + txtidAfp.Text, TypeMessageAlert.correct, false, "wfAFPBnd.aspx?Filter=1");

        }

        public override Object CreateEntitySet()
        {
            EAfp objE = new EAfp();

            if (this.FormEditAction == FormEditAction.AddNew || this.FormEditAction == FormEditAction.Copy)
                objE.EntityState = EntityState.Added;
            else
            {
                IBOQuery objBO = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(RHBOQry.Afp));
                objE.IdAfp = this.txtidAfp.Text;
                objE = (EAfp)objBO.GetByKey(objE);

                if (this.FormEditAction == FormEditAction.Edit)
                    objE.EntityState = EntityState.Modified;
                if (this.FormEditAction == FormEditAction.Delete)
                    objE.EntityState = EntityState.Deleted;

            }

            WebHelper.ControlToEntity(txtidAfp, objE, "IdAfp");
            WebHelper.ControlToEntity(txtdsAfp, objE, "DsAfp");
            WebHelper.ControlToEntity(txtdsAbrev, objE, "DsAbrev");
            objE.StAnulado = ConstFlagEstado.DESACTIVADO;

            DataTable dt = (DataTable)this.DataSource;

            this.ClearDeletedRow(this.DataSource, "stAnulado");
            IList<EAfpComi> colEAfpComi = new List<EAfpComi>();

            if (this.FormEditAction == FormEditAction.Delete)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    this.MarkDeletedRow(dr, "stAnulado");
                }
            }

            for (int intTypeUpd = 0; intTypeUpd <= 1; intTypeUpd++)
            {
                DataTable dtChange = null;
                if (intTypeUpd == 0)
                    dtChange = dt.GetChanges(DataRowState.Added);
                else
                    dtChange = dt.GetChanges(DataRowState.Modified);


                if (dtChange != null)
                {
                    foreach (DataRow drDet in dtChange.Rows)
                    {
                        EAfpComi objEDet = DataHelper.CopyDataRowToEntity<EAfpComi>(drDet, typeof(EAfpComi));

                        if (drDet.RowState == DataRowState.Added)
                            objEDet.EntityState = EntityState.Added;

                        if (drDet.RowState == DataRowState.Modified)
                        {
                            if (objEDet.StAnulado == ConstFlagEstado.DESACTIVADO)
                                objEDet.EntityState = EntityState.Modified;
                            else
                                objEDet.EntityState = EntityState.Deleted;
                        }

                        colEAfpComi.Add(objEDet);
                    }
                }
            }

            EAfpSet objESet = new EAfpSet();
            objESet.Afp = objE;
            objESet.AfpComi = colEAfpComi;

            return objESet;
        }

        public override void LockControls()
        {
            //if (this.FormEditAction == FormEditAction.Delete)
            //else  
        }

    }
}